import axios from "axios";
import store from '@/store'
import { useRouter } from "vue-router";
import { notification } from "ant-design-vue";

const router = useRouter();

const service = axios.create({
    // baseURL: 'http://localhost:8000',
    baseURL: '/api',
    timeout: 5000
})
// 请求拦截器
service.interceptors.request.use(
    config => {
        // 每次发送请求之前判断vuex中是否存在token
        const token = store.state.member.token
        if (token) {
            config.headers['token'] = token
        }
        return config
    },
    error => {
        return Promise.resolve(error)
    }
)
// 响应拦截器
service.interceptors.response.use(
    response => {
        return response.data
    },
    error => {
        // 未携带token，被网关拦截的响应
        const status = error.response.status
        if (status === 401) {
            store.commit("setMember", {})
            notification.error({ description: "未登录或登录超时" })
            router.push('/login')
        }
        console.log('返回错误：' + error)
        return Promise.resolve(error)
    }
)

export default service


